
const path = require("path");

const fs = require("fs");

const ResponseMessage = require("../response/message")

const promisify = require("../utils/promisify")

const rename = promisify(fs.rename)

const config = require("../config")

module.exports = (moduleName) => {
    return async (req,res,next) => {
        if(req.file){
            if(!fs.existsSync(path.resolve(__dirname,"../uploads/"+moduleName))){
               fs.mkdirSync(path.resolve(__dirname,"../uploads/"+moduleName));
            }
            const { mimetype,size } = req.file;
            if(!config.uploadTypes.includes(mimetype)){
                return res.send(new ResponseMessage(201,"只支持 jpg png 的图像格式",{}))
            }
            if(size > config.uploadSize){
                return res.send(new ResponseMessage(201,"请上传小于" + config.uploadSize + "字节的图片",{}))
            }
            try{
                const fileName = (Math.random()*size+1)+"".split(2)+path.extname(req.file.originalname);
                const avatarUrl = path.resolve(__dirname,"../uploads/"+moduleName+ "/" +fileName);
                await rename(path.resolve(__dirname,"../uploads/"+req.file.filename),avatarUrl);
                req.body[moduleName+"Avatar"] = config.protocal + "://"+config.hostname+":"+config.port+"/uploads/"+moduleName + "/" + fileName;
                next();
            }catch(error){
                res.send(new ResponseMessage(500,"上传错误",{msg:error.message}))
            }
        }else{
            next();
        }
    }
}